import subprocess
import time
from alg import bubble_sort


def run_tests():
    try:
        # 运行generator.py获取测试数据，明确指定utf-8编码
        result = subprocess.run(
            ['python', 'generator.py'],
            capture_output=True,
            text=True,
            encoding='utf-8'
        )

        # 检查是否有错误输出
        if result.stderr:
            print("运行generator.py时出错:")
            print(result.stderr)
            return

        output_lines = result.stdout.strip().split('\n')

        # 提取随机数列表
        for line in output_lines:
            if "随机数列表：" in line:
                random_nums_str = line.split("：")[1].strip()
                # 移除方括号并分割字符串
                elements = random_nums_str[1:-1].split(', ')
                # 转换为整数列表
                test_case = [int(num) for num in elements if num]
                break
        else:
            print("无法从generator.py输出中获取随机数列表")
            print("输出内容:", result.stdout)
            return

    except UnicodeDecodeError as e:
        print(f"解码错误: {e}")
        print("尝试使用不同的编码读取输出...")
        # 尝试使用系统默认编码再次读取
        result = subprocess.run(['python', 'generator.py'], capture_output=True)
        try:
            output = result.stdout.decode('gbk')
            print("使用GBK编码成功读取输出")
            output_lines = output.strip().split('\n')
            # 继续处理输出...
        except Exception as e2:
            print(f"再次尝试失败: {e2}")
            print("请检查generator.py的输出内容")
            return
    except Exception as e:
        print(f"执行测试时出错: {e}")
        return

    input_data = test_case.copy()

    # 计算期望结果
    expected = sorted(input_data)

    # 运行算法并计时
    start_time = time.time()
    result = bubble_sort(input_data)
    end_time = time.time()
    execution_time = end_time - start_time

    # 验证结果
    if result == expected:
        status = "✅ 成功"
    else:
        status = "❌ 失败"

    # 输出测试结果
    print("=" * 50)
    print("冒泡排序算法测试结果")
    print("=" * 50)
    print(f"测试用例: {status}")
    print(f"输入: {input_data}")
    print(f"输出: {result}")
    print(f"期望: {expected}")
    print(f"执行时间: {execution_time:.6f} 秒")
    print("=" * 50)

    if result == expected:
        print("🎉 测试通过!")
    else:
        print("❌ 测试未通过，请检查算法实现。")


if __name__ == "__main__":
    run_tests()